<template>
    <div>
        <!-- 搜索区域 -->
        <div class="search" v-show="isShowSearch">
            <div class="input">
                <label for="">客户姓名</label>
                <el-input placeholder="请输入客户姓名" v-model="searchParams.name" clearable
                    @clear="getClueListInfo"></el-input>
            </div>
            <div class="input">
                <label for="">客户手机</label>
                <el-input placeholder="请输入客户手机号码" v-model="searchParams.phone" clearable
                    @clear="getClueListInfo"></el-input>
            </div>
            <div class="input">
                <label for="">归属人</label>
                <el-input placeholder="请输入线索归属人" v-model="searchParams.owner" clearable
                    @clear="getClueListInfo"></el-input>
            </div>
            <div class="input">
                <label for="">渠道来源</label>
                <el-select v-model="searchParams.channelId" placeholder="渠道来源" size="large" style="width: 240px"
                    clearable @clear="getClueListInfo" @click="getChannelList">
                    <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                        :value="item.channelId" />
                </el-select>
            </div>
            <div class="input">
                <label for="">线索状态</label>
                <el-select v-model="searchParams.status" placeholder="线索状态" size="large" style="width: 240px" clearable
                    @clear="getClueListInfo" @click="getChannelList">
                    <el-option v-for="(item, index) in channelStatus" :key="index" :label="item.label"
                        :value="item.value" />
                </el-select>
            </div>
            <div class="input">
                <label for="">跟进时间</label>
                <el-date-picker clear @clear="getClueListInfo" v-model="searchParams.funTime" type="datetimerange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
            </div>
            <div class="input">
                <el-button type="primary" @click="getClueListInfo"><el-icon>
                        <Search />
                    </el-icon><span>搜索</span></el-button>
                <el-button @click="reset"><el-icon>
                        <Refresh />
                    </el-icon><span>重置</span></el-button>
            </div>
        </div>
        <div v-show="!isShowSearch"></div>

        <!-- 内容区域 -->
        <div class="content">
            <div class="ant">
                <div class="flex gap-2">
                    <el-button type="primary" @click="handleClue(), getChannelList()">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>新增</span>
                    </el-button>
                    <el-button type="success" :disabled="selectedClueIds.length != 1"
                        @click="handleClue(selectedClueIds)">
                        <el-icon>
                            <Edit />
                        </el-icon>
                        <span>修改</span>
                    </el-button>
                    <el-button type="danger" :disabled="selectedClueIds.length == 0" @click="handleDeleteClue">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        <span>删除</span>
                    </el-button>

                    <el-button type="warning" :disabled="selectedClueIds.length == 0" @click="handleExportClue">
                        <el-icon>
                            <Download />
                        </el-icon>
                        <span>导出</span>
                    </el-button>
                </div>
                <div class="ant-btn">
                    <el-tooltip :content="isShowSearch ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-button class="show" @click="handleShow">
                        <el-icon>
                            <Search />
                        </el-icon>
                    </el-button>
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">

                        <el-button class="show" @click="getClueListInfo">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                        </el-button>
                    </el-tooltip>
                </div>
            </div>
            <!-- 操作按钮 -->

            <!-- 表格 -->
            <div class="table">
                <el-table :data="clueList" @select="handleSelectionChange" @select-all="handleSelectAll"
                    reserve-selection>
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column fixed prop="clueId" label="线索编号" width="80" align="center" />
                    <el-table-column prop="name" label="客户姓名" width="120" align="center" />
                    <el-table-column prop="phone" label="手机号码" :rules="[{ required: true, message: '请输入手机号码' }]"
                        width="120" align="center" />
                    <el-table-column prop="channelName" label="渠道来源" width="120" align="center" />
                    <!-- <el-table-column prop="formdata.formDate(createTime)" label="创建时间" /> -->
                    <el-table-column label="创建时间" width="180" align="center">
                        <template #default="scope">
                            {{ formdata.formDate(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="owner" label="线索归属" width="120" align="center" />
                    <!-- <el-table-column prop="status" label="线索状态" /> -->
                    <el-table-column label="线索状态" width="150" align="center">
                        <template #default="scope">
                            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                                {{ getStatusLabel(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="nextTime" label="下次跟进时间"  /> -->
                    <el-table-column label="下次跟进时间" width="180" align="center">
                        <template #default="scope">
                            {{ formdata.formDate(scope.row.nextTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="handleDetail(scope.row)"><el-icon><View /></el-icon>查看</el-button>
                            <el-button v-if="scope.row.status == 1" link type="primary" size="small"
                                @click="handleAssign(scope.row)"><el-icon><Pointer /></el-icon>分配</el-button>
                            <el-button v-if="scope.row.status == 2 || scope.row.status == 1" link type="primary"
                                size="small" @click="handleFollow(scope.row)"><el-icon><TopRight /></el-icon>跟进</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <pagination v-show="total > 0" v-model:page="searchParams.pageNum" v-model:limit="searchParams.pageSize"
                    :total="total" @pagination="getClueListInfo" class="page-box" />
            </div>

            <!-- 增加/编辑 -->
            <el-dialog v-model="dialogFormVisible" class="add" :title="selectedClueIds ? '编辑线索' : '新增线索'" width="700">
                <el-form ref="formListRef" :model="formList" :rules="rules" :size="formSize">
                    <el-form-item label="手机号码" :label-width="formLabelWidth" prop="phone">
                        <el-input v-model="formList.phone" placeholder="请输入手机号码" autocomplete="off"
                            input-style="width: 200px" />
                    </el-form-item>
                    <el-form-item label="客户姓名" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="formList.name" placeholder="请输入客户姓名" autocomplete="off"
                            input-style="width: 200px" />
                    </el-form-item>
                    <el-form-item label="渠道来源" :label-width="formLabelWidth">
                        <el-select v-model="formList.channelId" placeholder="渠道来源" style="width: 200px">
                            <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                                :value="item.channelId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="活动信息" :label-width="formLabelWidth">
                        <el-select v-model="formList.activityId" @click="getActivityInfo" placeholder="活动信息"
                            style="width: 200px">
                            <el-option v-for="item in activityInfo" :key="item.activityId" :label="item.name"
                                :value="item.activityId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户性别" :label-width="formLabelWidth">
                        <el-radio-group v-model="formList.gender">
                            <el-radio :label="1" value="1">男</el-radio>
                            <el-radio :label="0" value="0">女</el-radio>
                            <el-radio>未知</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="客户年龄" :label-width="formLabelWidth">
                        <el-input-number v-model="formList.age" placeholder="年龄" :min="0" />
                    </el-form-item>
                    <el-form-item label="微信号码" :label-width="formLabelWidth">
                        <el-input v-model="formList.weixin" placeholder="请输入微信号码" autocomplete="off"
                            input-style="width: 200px" />
                    </el-form-item>
                    <el-form-item label="QQ号码" :label-width="formLabelWidth">
                        <el-input v-model="formList.qq" placeholder="请输入QQ号码" autocomplete="off"
                            input-style="width: 200px" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button v-if="selectedClueIds.length != 0" type="primary"
                            @click="updateClueInfo(formListRef)">
                            确定
                        </el-button>
                        <el-button v-else type="primary" @click="addClueInfo(formListRef)"> 确定 </el-button>

                        <el-button @click="dialogFormVisible = false">取消</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 分配 -->
            <el-dialog v-model="dialogClueVisible" title="分配线索" width="700">
                <div class="assign-form">
                    <el-form :model="assignForm" :rules="rules" ref="formListRef">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="归属部门" prop="deptId">
                                    <el-tree-select v-model="assignForm.deptId" :data="departmentList" node-key="id"
                                        placeholder="请选择归属部门" style="width: 240px" check-strictly />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="分配给" prop="userId">
                                    <el-select v-model="assignForm.userId" placeholder="选择用户" style="width: 200px"
                                        @click="handleVoidAssign">
                                        <el-option v-for="item in assignList" :key="item.userId" :label="item.nickName"
                                            :value="item.userId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>

                <div class="assign-btn">
                    <el-button type="primary" @click="handleVoidConfirm(formListRef)">确定</el-button>
                    <el-button @click="dialogClueVisible = false">取消</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch } from 'vue';
import {
    getClueList,
    getClueChannel,
    addClue,
    getClueInfo,
    editClue,
    deleteClue,
    getActivityDetail,
    getClueChannelStatus,
    getClueDepartment,
    getClueDepartmentUser,
    getAssign,
} from '@/api/tienchin/clue';
import { formdata } from '@/api/format';
import { ComponentSize, FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus';
import * as XLSX from 'xlsx';
import router from '@/router';

// 搜索参数
const searchParams = ref({
    name: '',
    phone: '',
    createBy: '',
    channelId: '',
    status: '',
    nextTime: '',
    funTime: [],
    pageNum: 1,
    pageSize: 10,
});

const formList = ref({
    activityId: '',
    age: '年龄',
    channelId: 1,
    clueId: 0,
    createBy: '',
    createTime: '',
    delFlag: 0,
    endTime: '',
    failCount: 0,
    gender: 0,
    level: 0,
    name: '',
    nextTime: '',
    phone: '',
    qq: '',
    remark: 0,
    status: 1,
    subject: 0,
    transfer: true,
    updateBy: '',
    updateTime: '',
    weixin: '',
});


const assignForm = ref({
    aid: 0,
    assignId: 0,
    createBy: '',
    createTime: '',
    deptId: 0,
    latest: true,
    remark: '',
    type: 0,
    updateBy: '',
    updateTime: '',
    userId: 0,
    userName: '',
});
const formSize = ref<ComponentSize>('default');
const activityInfo = ref([]);
const formListRef = ref<FormInstance>();

const rules = reactive<FormRules>({
    phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
    deptId: [{ required: true, message: '请选择归属部门', trigger: 'change' }],
    userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
});
// 数据
const selectedClueIds = ref([]);
const formLabelWidth = ref('120px');
const clueList = ref([]);
const channelList = ref([]);
const channelStatus = ref([]);
const departmentList = ref([]);
const assignList = ref([]);

const total = ref();
const dialogFormVisible = ref(false);
const dialogClueVisible = ref(false);
const isShowSearch = ref(true);

function handleShow() {
    isShowSearch.value = !isShowSearch.value;
}

// 获取状态标签
function getStatusLabel(status: string) {
    const statusObj = channelStatus.value.find(item => item.value == status);
    return statusObj ? statusObj.label : '';
}

// 获取状态标签的颜色
function getStatusTagType(status: string) {
    const statusObj = channelStatus.value.find(item => item.value == status);
    switch (statusObj?.value) {
        case '0':
            return 'danger';
        case '1':
            return 'primary';
        case '2':
            return 'success';
        case '3':
            return 'primary';
        case '4':
            return 'warning';
        default:
            return '';
    }
}

function getClueListInfo() {
    getClueList(searchParams.value).then(res => {
        console.log(res);
        clueList.value = res.rows;
        // clueList.value.createTime = formdata.formDate(res.rows.createTime);
        total.value = res.total;
    });
    getClueChannelStatus().then(res => {
        console.log(res.data);
        channelStatus.value = res.data.map(item => {
            return {
                label: item.dictLabel,
                value: item.dictValue,
            };
        });
        console.log(channelStatus.value);
    });
}

function getChannelList() {
    getClueChannel().then(res => {
        console.log(res);
        channelList.value = res.data;
        console.log(channelList.value);

    });
}
function getActivityInfo() {
    getActivityDetail(formList.value.channelId).then(res => {
        console.log(res);
        activityInfo.value = res.data;
    });
}
const updateClueInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(valid => {
        if (valid) {
            editClue(formList.value).then(res => {
                console.log(res);
                if (res.code != 200) return ElMessage.error('更新线索失败');
                ElMessage.success('更新线索成功');
                console.log(res);
                dialogFormVisible.value = false;
                selectedClueIds.value = [];
                getClueListInfo();
            });
            console.log('submit!');
        } else {
            console.log('error submit!');
        }
    });
};
const addClueInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(valid => {
        if (valid) {
            addClue(formList.value).then(res => {
                if (res.code != 200) return ElMessage.error('添加线索失败');
                ElMessage.success('添加线索成功');
                console.log(res);
                dialogFormVisible.value = false;
                getClueListInfo();
            });
            console.log('submit!');
        } else {
            console.log('error submit!');
        }
    });
};
const reset = () => {
    searchParams.value = {
        name: '',
        phone: '',
        createBy: '',
        channelId: '',
        status: '',
        nextTime: '',
        funTime: [],
        pageNum: 1,
        pageSize: 10,
    };
    getClueListInfo();
};

watch(() => assignForm.value.deptId, () => {
    assignForm.value.userId = '';
}
);

const handleVoidConfirm = async (formEl: FormInstance | undefined) => {
    console.log(123);

    if (!formEl) return;
    formEl.validate(valid => {
        if (valid) {
            getAssign(assignForm.value).then(res => {
                console.log(res);
                if (res.code != 200) return ElMessage.error('分配线索失败');
                ElMessage.success('分配线索成功');
                dialogClueVisible.value = false;
                getClueListInfo();
            });
            console.log('submit!');
        } else {
            console.log('error submit!');
        }
    });
};
function handleAssign(row) {
    dialogClueVisible.value = true;

    // assignForm.value.userId = '';
    // assignForm.value.deptId = '';
    console.log(row);
    getClueDepartment().then(res => {
        console.log(res);
        departmentList.value = res.data;
        handleVoidAssign();
    });
}

function handleVoidAssign() {
    getClueDepartmentUser(assignForm.value.deptId).then(res => {
        console.log(res);
        assignList.value = res.data;
    });
}

function handleDetail(row) {
    console.log(row.clueId);
    router.push({ path: '/clueDetail', query: { id: row.clueId, status: 'view' } });
}
function handleFollow(row) {
    console.log(row.clueId);
    router.push({ path: '/clueDetail', query: { id: row.clueId, status: 'follow' } });
}

function handleDeleteClue() {
    ElMessageBox.confirm(`是否删除线索编号为${selectedClueIds.value.join(',')}的数据项`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        deleteClue(selectedClueIds.value)
            .then(res => {
                if (res.code != 200) return ElMessage.error('删除线索失败');
                ElMessage.success('删除线索成功');
                selectedClueIds.value = [];
                console.log(res);
                getClueListInfo();
            })
            .catch(() => {
                ElMessage.info('取消删除');
            });
    });
}
function handleSelectAll(selection) {
    if (selection.length) {
        // 如果有选中的项，则将所有clueId添加到selectedClueIds
        selectedClueIds.value = selection.map(item => item.clueId);
    } else {
        // 如果没有选中的项，则清空selectedClueIds
        selectedClueIds.value = [];
    }
    console.log(selectedClueIds.value);
}
function handleSelectionChange(selection) {
    console.log(selectedClueIds.value.length);

    if (selection.length) {
        // 如果有选中的项，则更新selectedClueIds
        selectedClueIds.value = selection.map(item => item.clueId);
    } else {
        // 如果没有选中的项，则清空selectedClueIds
        selectedClueIds.value = [];
    }
    console.log(selectedClueIds.value);
    console.log(selectedClueIds);
}
const handleClue = e => {
    console.log(e);
    dialogFormVisible.value = true;

    if (e) {
        getChannelList();
        getClueInfo(e).then(res => {
            console.log(res);
            formList.value.channelId = res.data.channelId;
            formList.value.name = res.data.name;
            formList.value.phone = res.data.phone;
            formList.value.weixin = res.data.weixin;
            formList.value.qq = res.data.qq;
            formList.value.remark = res.data.remark;
            formList.value.gender = res.data.gender;
            formList.value.age = res.data.age;
            formList.value.clueId = res.data.clueId;
        });
    } else {
        formList.value = {
            activityId: '',
            age: '年龄',
            channelId: '',
            clueId: 0,
            createBy: '',
            createTime: '',
            delFlag: 0,
            endTime: '',
            failCount: 0,
            gender: 0,
            level: 0,
            name: '',
            nextTime: '',
            phone: '',
            qq: '',
            remark: 0,
            status: 1,
            subject: 0,
            transfer: true,
            updateBy: '',
            updateTime: '',
            weixin: '',
        };
    }
};

const handleExportClue = async () => {
    if (selectedClueIds.value.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }

    try {
        // 假设有一个API可以获取指定ID的线索详情
        const response = await getSelectedClueDetails(selectedClueIds.value);
        const selectedClues = response.data;

        // 将数据转换为Excel格式
        const worksheet = XLSX.utils.json_to_sheet(selectedClues);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '线索管理信息表');

        // 下载文件
        XLSX.writeFile(workbook, '线索管理信息表.xlsx');
    } catch (error) {
        ElMessage.error('导出数据失败');
        console.error(error);
    }
};

// 假设的API调用，用于获取选中的线索详情
async function getSelectedClueDetails(clueIds: number[]) {
    // 这里应该是实际的API调用
    // 示例返回值
    return {
        data: clueList.value.filter(clue => clueIds.includes(clue.clueId)),
    };
}

// 初始加载数据
onMounted(() => {
    getClueListInfo();
});

// 监听页码或页面大小变化，自动重新请求数据
// watch([currentPage, pageSize], () => {
//     fetchClueList();
// });
</script>

<style scoped lang="scss">
.search {
    display: flex;
    flex-wrap: wrap;
    min-width: 1500px;

    .input {
        margin: 20px 40px;
        display: flex;
        align-items: center;

        .el-input {
            width: 200px;
        }

        label {
            margin-right: 10px;
        }
    }
}

::v-deep .content {
    margin-left: 20px;

    .ant {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        .gap-2 {
            margin: 10px 0;
            display: flex;
            // justify-content: space-between;

            .el-tag {
                width: 80px;
                font-size: 14px;
                display: flex;
                align-items: center;
                justify-content: center;

                span {
                    margin-left: 5px;
                }
            }
        }

        .ant-btn {
            margin-right: 20px;
            
        }
    }


    .assgin-form {
        margin-left: 20px;
        display: flex;
        padding: 0;
    }

    .table {
        width: 100%;

        .pagination-container .el-pagination {
            right: 20px;
        }
    }
}

.add {
    .el-form {
        display: flex;
        flex-wrap: wrap;
    }
}

.assign-form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.department,
.assign {
    display: flex;
    align-items: center;
}

.department label,
.assign label {
    width: 80px;
    padding-right: 12px;
    text-align: center;
    // margin-right: 10px;
}

.assign-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 60px;
}

.show {
    border-radius: 50%;
    width: 33px;
    height: 33px;
}
</style>
